package cn.net.zyx.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * description: BlockExceptionHandler <br>
 * date: 2021/5/14 14:35 <br>
 *
 * @author: ZhangYixin <br>
 * version: 1.0 <br>
 */
@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        HashMap<String, Object> hashMap = new HashMap<>(4);
        if (e instanceof FlowException){
            hashMap.put("code",-1);
            hashMap.put("msg","限流异常");
        }
        if (e instanceof DegradeException){
            hashMap.put("code",-2);
            hashMap.put("msg","降级异常");
        }
        if (e instanceof ParamFlowException){
            hashMap.put("code",-3);
            hashMap.put("msg","热点参数异常");
        }
        if (e instanceof SystemBlockException){
            hashMap.put("code",-4);
            hashMap.put("msg","系统规则异常");
        }
        if (e instanceof AuthorityException){
            hashMap.put("code",-5);
            hashMap.put("msg","授权异常");
        }

//        设置返回json
        httpServletResponse.setStatus(200);
        httpServletResponse.setHeader("Content-type","application/json;charset=UTF-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(hashMap));


    }
}
